<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">校园智慧竞赛平台 - 管理后台</h1>
      </div>
      <div class="header-right">
        <span class="admin-name">{{ adminName }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" @click="navigateTo('/dashboard')">
            <i class="icon">📊</i>
            <span>仪表盘</span>
          </div>
          <div class="menu-item" @click="navigateTo('/user-audit')">
            <i class="icon">👥</i>
            <span>用户审核</span>
          </div>
          <div class="menu-item active">
            <i class="icon">👤</i>
            <span>用户管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/team-management')">
            <i class="icon">⚡</i>
            <span>队伍管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/homepage-editor')">
            <i class="icon">🏠</i>
            <span>主页编辑</span>
          </div>
          <div class="menu-item" @click="navigateTo('/system-notifications')">
            <i class="icon">📢</i>
            <span>通知管理</span>
          </div>
          <div class="menu-item" @click="navigateTo('/news-management')">
            <i class="icon">📰</i>
            <span>新闻管理</span>
          </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <i class="icon">🏆</i>
          <span>赛事管理</span>
        </div>
        </nav>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content">
        <div class="page-header">
          <h2>用户管理</h2>
          <div class="header-actions">
            <div class="search-box">
              <input
                v-model="searchKeyword"
                type="text"
                placeholder="搜索用户姓名、学号或工号"
                class="search-input"
                @keyup.enter="handleSearch"
              />
              <button class="search-btn" @click="handleSearch">搜索</button>
            </div>
            <div class="filter-tabs">

              <button
                class="tab-btn"
                :class="{ active: statusFilter === 'all' && currentTab === 'all' }"
                @click="switchToAllUsers()"
              >
                全部用户
              </button>
              <button
                class="tab-btn"
                :class="{ active: statusFilter === 'all' && currentTab === 'teachers' }"
                @click="switchTab('teachers')"
              >
                教师库 ({{ teacherTotal }})
              </button>
              <button
                class="tab-btn"
                :class="{ active: statusFilter === 'all' && currentTab === 'students' }"
                @click="switchTab('students')"
              >
                学生库 ({{ studentTotal }})
              </button>
            </div>
            <div class="status-filters">
              <button
                class="status-btn"
                :class="{ active: statusFilter === 'rejected' }"
                @click="switchStatusFilter('rejected')"
                title="查看审核被驳回的用户（账号已禁用）"
              >
                驳回记录
              </button>
              <button
                class="status-btn"
                :class="{ active: statusFilter === 'deactivated' }"
                @click="switchStatusFilter('deactivated')"
              >
                注销记录
              </button>
            </div>
            <div class="export-actions">
              <button 
                class="export-btn"
                :class="{ loading: isExporting }"
                @click="handleExportData"
                :disabled="isExporting"
              >
                <span v-if="isExporting">导出中...</span>
                <span v-else>📊 导出当前数据</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 状态说明 -->
        <div v-if="statusFilter === 'all'" class="status-info">
          <div class="info-icon">ℹ️</div>
          <div class="info-text">
            <strong>数据说明：</strong>以下为所有审核过（通过/驳回）的用户数据，点击用户可查看详情
          </div>
        </div>

        <div v-if="statusFilter === 'rejected'" class="status-info">
          <div class="info-icon">ℹ️</div>
          <div class="info-text">
            <strong>驳回记录说明：</strong>以下用户的注册申请已被驳回，其账号状态已被禁用
          </div>
        </div>

        <div v-if="statusFilter === 'deactivated'" class="status-info">
          <div class="info-icon">ℹ️</div>
          <div class="info-text">
            <strong>注销记录说明：</strong>以下用户的注册申请已被注销，其账号状态已被禁用
          </div>
        </div>

        <!-- 用户列表 -->
        <div class="user-list">
          <div v-if="loading" class="loading">
            加载中...
          </div>
          
          <div v-else-if="currentUsers.length === 0" class="empty-state">
            <div class="empty-icon">👤</div>
            <p>{{ searchKeyword ? '未找到匹配的用户' : '暂无用户数据' }}</p>
          </div>
          
          <div v-else class="user-table">
            <table>
              <thead>
                <tr>
                  <th></th>
                  <th>姓名</th>
                  <th>{{ currentTab === 'all' ? '编号' : (currentTab === 'teachers' ? '工号' : '学号') }}</th>
                  <th>{{ currentTab === 'all' ? '类型/信息' : (currentTab === 'teachers' ? '职位' : '学院') }}</th>
                  <th>审核状态</th>
                  <th>账号状态</th>
                  <th>注册时间</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in currentUsers" :key="user.id" class="user-row clickable-row" @click="viewUserDetail(user)" title="点击查看详情">
                  <td>
                    <div class="user-avatar">
                      <img v-if="user.avatar" :src="user.avatar" :alt="user.realName" />
                      <div v-else class="avatar-placeholder">
                        {{ user.realName ? user.realName.charAt(0) : '?' }}
                      </div>
                    </div>
                  </td>
                  <td class="user-name">{{ user.realName || '未填写' }}</td>
                  <td class="user-id">{{ user.loginId }}</td>
                  <td>
                    <!-- 根据当前标签页显示不同内容 -->
                    <span v-if="currentTab === 'all'">
                      <span class="user-type-badge" :class="user.userType === 1 ? 'teacher' : 'student'">
                        {{ user.userType === 1 ? '教师' : '学生' }}
                      </span>
                      <br>
                      <small>{{ user.userType === 1 ? (user.professionalTitle || '未填写') : (user.college || '未填写') }}</small>
                    </span>
                    <span v-else-if="user.userType === 1">{{ user.professionalTitle || '未填写' }}</span>
                    <span v-else>{{ user.college || '未填写' }}</span>
                  </td>
                  <td>
                    <span class="status-badge" :class="getAuditStatusClass(user.auditStatus)">
                      {{ getAuditStatusText(user.auditStatus) }}
                    </span>
                  </td>
                  <td>
                    <span class="status-badge" :class="getAccountStatusClass(user.status)">
                      {{ getAccountStatusText(user.status) }}
                    </span>
                  </td>
                  <td class="create-time">{{ formatTime(user.createTime) }}</td>
                  <td>
                    <div class="user-actions" @click.stop>
                      <button
                      class="edit-btn"
                      @click.stop="editUser(user)"
                      v-if="user.status === 1 && user.auditStatus === 1"
                      >
                        编辑
                      </button>
                      <button
                        v-if="user.status === 1 && user.auditStatus === 1"
                        class="deactivate-btn"
                        @click.stop="handleDeactivate(user)"
                        :disabled="processing"
                      >
                        注销
                      </button>
                      <!-- <button
                        v-else
                        class="activate-btn"
                        @click="handleActivate(user)"
                        :disabled="processing"
                      >
                        启用
                      </button> -->
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="totalPages > 1">
          <button 
            class="page-btn" 
            :disabled="currentPage === 1" 
            @click="changePage(currentPage - 1)"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button 
            class="page-btn" 
            :disabled="currentPage === totalPages" 
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </main>
    </div>

    <!-- 用户详情弹窗 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal-content large" @click.stop>
        <div class="modal-header">
          <h3>用户详情</h3>
          <button class="close-btn" @click="closeDetailModal">×</button>
        </div>
        <div class="modal-body">
          <div class="detail-content" v-if="selectedUser">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>姓名：</label>
                  <span>{{ selectedUser.realName || '未填写' }}</span>
                </div>
                <div class="detail-item">
                  <label>用户类型：</label>
                  <span>{{ selectedUser.userTypeName || (selectedUser.userType === 1 ? '教师' : '学生') }}</span>
                </div>
                <div class="detail-item">
                  <label>{{ selectedUser.userType === 1 ? '工号' : '学号' }}：</label>
                  <span>{{ selectedUser.loginId }}</span>
                </div>
                <div class="detail-item">
                  <label>用户名：</label>
                  <span>{{ selectedUser.username || '未填写' }}</span>
                </div>
                <div class="detail-item" v-if="selectedUser.userType === 1">
                  <label>手机号：</label>
                  <span>{{ selectedUser.phone || '未填写' }}</span>
                </div>
                <div class="detail-item">
                  <label>邮箱：</label>
                  <span>{{ selectedUser.email || '未填写' }}</span>
                </div>
                <div class="detail-item" v-if="selectedUser.userType === 1">
                  <label>职位：</label>
                  <span>{{ selectedUser.professionalTitle || '未填写' }}</span>
                </div>
                <div class="detail-item" v-if="selectedUser.userType === 2">
                  <label>学院：</label>
                  <span>{{ selectedUser.college || '未填写' }}</span>
                </div>
                <div class="detail-item">
                  <label>年龄：</label>
                  <span>{{ selectedUser.age || '未填写' }}</span>
                </div>
                <div class="detail-item" v-if="selectedUser.userType === 1">
                  <label>身份证号：</label>
                  <span>{{ selectedUser.idCard || '未填写' }}</span>
                </div>
              </div>
            </div>

            <!-- 技能信息 -->
            <div class="detail-section" v-if="selectedUser.userType === 2">
              <h4>技能信息</h4>
              <div class="detail-item">
                <label>掌握技能：</label>
                <div class="skills-display">
                  <template v-if="selectedUser.skills && selectedUser.skills.length > 0">
                    <span
                      v-for="(skill, index) in selectedUser.skills"
                      :key="index"
                      class="skill-badge"
                      :title="typeof skill === 'string' ? skill : skill.name"
                    >
                      {{ typeof skill === 'string' ? skill : skill.name }}
                    </span>
                  </template>
                  <span v-else class="no-skills">暂无技能信息</span>
                </div>
              </div>
            </div>
            
            <div class="detail-section">
              <h4>状态信息</h4>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>审核状态：</label>
                  <span class="status-badge" :class="getAuditStatusClass(selectedUser.auditStatus)">
                    {{ selectedUser.auditStatusName || getAuditStatusText(selectedUser.auditStatus) }}
                  </span>
                </div>
                <div class="detail-item">
                  <label>账号状态：</label>
                  <span class="status-badge" :class="getAccountStatusClass(selectedUser.status)">
                    {{ selectedUser.statusName || getAccountStatusText(selectedUser.status) }}
                  </span>
                </div>
                <div class="detail-item">
                  <label>注册时间：</label>
                  <span>{{ formatTime(selectedUser.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <label>最后更新：</label>
                  <span>{{ formatTime(selectedUser.updateTime) }}</span>
                </div>
              </div>
            </div>

            <!-- 审核信息 -->
            <div class="detail-section" v-if="selectedUser.auditStatus !== 0">
              <h4>审核信息</h4>
              <div class="detail-grid">
                <div class="detail-item" v-if="selectedUser.auditTime">
                  <label>审核时间：</label>
                  <span>{{ formatTime(selectedUser.auditTime) }}</span>
                </div>
                <div class="detail-item" v-if="selectedUser.auditReason">
                  <label>驳回原因：</label>
                  <span>{{ selectedUser.auditReason }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeDetailModal">关闭</button>
        </div>
      </div>
    </div>

    <!-- 确认操作弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeConfirmModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ confirmModal.title }}</h3>
          <button class="close-btn" @click="closeConfirmModal">×</button>
        </div>
        <div class="modal-body">
          <p>{{ confirmModal.message }}</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeConfirmModal">取消</button>
          <button 
            class="confirm-btn" 
            :class="confirmModal.type" 
            @click="confirmAction"
            :disabled="processing"
          >
            {{ processing ? '处理中...' : '确定' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 用户编辑弹窗 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <div class="modal-content edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑用户信息</h3>
          <button class="close-btn" @click="closeEditModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveUserInfo">
            <div class="form-section">
              <h4>基本信息</h4>
              <div class="form-grid">
                <div class="form-item">
                  <label>姓名 *</label>
                  <input
                    v-model="editForm.realName"
                    type="text"
                    required
                    placeholder="请输入真实姓名"
                    maxlength="50"
                  />
                </div>
                <div class="form-item" v-if="editForm.userType === 1">
                  <label>手机号</label>
                  <input
                    v-model="editForm.phone"
                    type="tel"
                    placeholder="请输入手机号"
                  />
                </div>
                <div class="form-item">
                  <label>邮箱 *</label>
                  <input
                    v-model="editForm.email"
                    type="email"
                    required
                    placeholder="请输入邮箱地址"
                    maxlength="100"
                  />
                </div>
                <div class="form-item" v-if="editForm.userType === 1">
                  <label>职位</label>
                  <input
                    v-model="editForm.professionalTitle"
                    type="text"
                    placeholder="请输入职位"
                  />
                </div>
                <div class="form-item" v-if="editForm.userType === 2">
                  <label>学院</label>
                  <input
                    v-model="editForm.college"
                    type="text"
                    placeholder="请输入学院"
                  />
                </div>
                <div class="form-item" v-if="editForm.userType === 2">
                  <label>年龄</label>
                  <input
                    v-model.number="editForm.age"
                    type="number"
                    min="16"
                    max="100"
                    placeholder="请输入年龄"
                  />
                </div>
                <div class="form-item" v-if="editForm.userType === 1">
                  <label>身份证号</label>
                  <input
                    v-model="editForm.idCard"
                    type="text"
                    placeholder="请输入身份证号"
                  />
                </div>
              </div>
            </div>

            <div class="form-section" v-if="editForm.userType === 2">
              <h4>技能信息</h4>
              <div class="skills-section">
                <div v-if="skillsLoading" class="skills-loading">
                  <p style="color: #999; font-size: 14px;">正在加载技能列表...</p>
                </div>

                <div v-else class="skill-tags">
                  <span
                    v-for="skill in availableSkills"
                    :key="skill.id"
                    class="skill-tag"
                    :class="{ active: editForm.skillIds.includes(skill.id) }"
                    @click="toggleSkill(skill.id)"
                    :title="skill.name"
                  >
                    {{ skill.name || '未知技能' }}
                  </span>

                  <div v-if="availableSkills.length === 0" class="no-skills-available">
                    <p style="color: #999; font-size: 14px;">暂无可选技能</p>
                  </div>
                </div>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button
            class="confirm-btn save"
            @click="saveUserInfo"
            :disabled="processing"
          >
            {{ processing ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { ElMessage } from 'element-plus'
import {
  getTeachersService,
  getStudentsService,
  deactivateUserService,
  activateUserService,
  searchUsersService,
  getUserDetailService,
  updateUserService,
  getRejectedUsersService,
  getDeactivatedUsersService,
  getSkillsListService,
  exportRejectedUsersService,
  exportDeactivatedUsersService,
  exportAllUsersService
} from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const loading = ref(false)
const processing = ref(false)
const currentTab = ref('all') // 默认显示全部用户
const searchKeyword = ref('')
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = 10
const statusFilter = ref('all') // 状态筛选：all, rejected, deactivated

// 用户数据
const teachers = ref([])
const students = ref([])
const teacherTotal = ref(0)
const studentTotal = ref(0)
const rejectedUsers = ref([])
const deactivatedUsers = ref([])

// 当前显示的用户列表
const currentUsers = computed(() => {
  let allUsers = []

  if (statusFilter.value === 'rejected') {
    allUsers = rejectedUsers.value
  } else if (statusFilter.value === 'deactivated') {
    allUsers = deactivatedUsers.value
  } else if (currentTab.value === 'all') {
    // 显示所有用户（教师+学生）
    allUsers = [...teachers.value, ...students.value]
  } else {
    allUsers = currentTab.value === 'teachers' ? teachers.value : students.value
  }

  // 实现前端分页
  const startIndex = (currentPage.value - 1) * pageSize
  const endIndex = startIndex + pageSize
  const pagedUsers = allUsers.slice(startIndex, endIndex)

  console.log(`分页信息 - 当前页: ${currentPage.value}, 每页: ${pageSize}, 总数据: ${allUsers.length}, 显示: ${pagedUsers.length}条 (${startIndex + 1}-${Math.min(endIndex, allUsers.length)})`) // 调试信息

  return pagedUsers
})

// 弹窗状态
const showDetailModal = ref(false)
const showConfirmModal = ref(false)
const showEditModal = ref(false)
const selectedUser = ref(null)
const confirmModal = ref({
  title: '',
  message: '',
  type: '',
  user: null
})

// 编辑表单数据
const editForm = ref({
  id: null,
  userType: null,
  realName: '',
  email: '',
  phone: '',
  professionalTitle: '',
  idCard: '',
  college: '',
  age: null,
  skillIds: []
})

// 可用技能列表（从后端动态加载）
const availableSkills = ref([])
const skillsLoading = ref(false)

// 导出状态
const isExporting = ref(false)

// 加载技能列表
const loadSkillsList = async () => {
  skillsLoading.value = true
  try {
    console.log('开始加载技能列表...') // 调试信息
    const result = await getSkillsListService()
    console.log('技能列表API返回:', result) // 调试信息

    if (result.code === 200) {
      // 处理后端返回的技能数据，确保格式统一
      const skillsData = result.data || []
      availableSkills.value = skillsData.map(skill => ({
        id: skill.id,
        name: skill.name || skill.skillName || skill.title // 兼容不同的字段名
      }))
      console.log('技能列表加载成功:', availableSkills.value) // 调试信息
    } else {
      console.error('获取技能列表失败:', result.message)
      ElMessage.error('获取技能列表失败')
      // 使用备用的模拟数据
      availableSkills.value = [
        { id: 1, name: 'Java编程' },
        { id: 2, name: 'Python编程' },
        { id: 3, name: 'JavaScript' },
        { id: 4, name: '数据库设计' },
        { id: 5, name: '前端开发' },
        { id: 6, name: '后端开发' },
        { id: 7, name: '移动开发' },
        { id: 8, name: '数据分析' }
      ]
    }
  } catch (error) {
    console.error('加载技能列表失败:', error)
    ElMessage.error('加载技能列表失败')
    // 使用备用的模拟数据
    availableSkills.value = [
      { id: 1, name: 'Java编程' },
      { id: 2, name: 'Python编程' },
      { id: 3, name: 'JavaScript' },
      { id: 4, name: '数据库设计' },
      { id: 5, name: '前端开发' },
      { id: 6, name: '后端开发' },
      { id: 7, name: '移动开发' },
      { id: 8, name: '数据分析' }
    ]
  } finally {
    skillsLoading.value = false
  }
}



// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}



// 切换到全部用户
const switchToAllUsers = () => {
  currentTab.value = 'all'
  statusFilter.value = 'all'
  currentPage.value = 1
  loadUserData()
}

// 切换标签页
const switchTab = (tab) => {
  currentTab.value = tab
  currentPage.value = 1
  // 当点击第一组按钮时，重置状态筛选为'all'
  statusFilter.value = 'all'
  loadUserData()
}

// 搜索处理
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    // 如果搜索关键词为空，重新加载数据
    currentPage.value = 1
    loadUserData()
    return
  }

  loading.value = true
  try {
    const searchData = {
      keyword: searchKeyword.value.trim()
    }

    const result = await searchUsersService(searchData)
    if (result.code === 200) {
      const searchResults = result.data || []

      if (statusFilter.value === 'all') {
        if (currentTab.value === 'all') {
          // 搜索全部用户
          teachers.value = searchResults.filter(user => user.userType === 1)
          students.value = searchResults.filter(user => user.userType === 2)
          teacherTotal.value = teachers.value.length
          studentTotal.value = students.value.length
          // 计算总页数
          const totalUsers = teacherTotal.value + studentTotal.value
          totalPages.value = Math.ceil(totalUsers / pageSize)
        } else if (currentTab.value === 'teachers') {
          teachers.value = searchResults.filter(user => user.userType === 1)
          teacherTotal.value = teachers.value.length
          totalPages.value = Math.ceil(teacherTotal.value / pageSize)
        } else {
          students.value = searchResults.filter(user => user.userType === 2)
          studentTotal.value = students.value.length
          totalPages.value = Math.ceil(studentTotal.value / pageSize)
        }
      } else if (statusFilter.value === 'rejected') {
        rejectedUsers.value = searchResults.filter(user => user.auditStatus === 2)
        totalPages.value = Math.ceil(rejectedUsers.value.length / pageSize)
      } else if (statusFilter.value === 'deactivated') {
        deactivatedUsers.value = searchResults.filter(user => user.status === 0)
        totalPages.value = Math.ceil(deactivatedUsers.value.length / pageSize)
      }
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 切换状态筛选
const switchStatusFilter = async (filter) => {
  statusFilter.value = filter
  currentPage.value = 1
  searchKeyword.value = '' // 清空搜索关键词

  // 当点击第二组按钮（rejected或deactivated）时，重置currentTab
  if (filter === 'rejected' || filter === 'deactivated') {
    currentTab.value = 'all' // 重置为全部用户
  }

  if (filter === 'rejected') {
    await loadRejectedUsers()
  } else if (filter === 'deactivated') {
    await loadDeactivatedUsers()
  } else {
    await loadUserData()
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '未知'
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

// 获取审核状态样式
const getAuditStatusClass = (status) => {
  const classes = {
    0: 'pending',
    1: 'approved',
    2: 'rejected'
  }
  return classes[status] || 'unknown'
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '已通过',
    2: '已驳回'
  }
  return texts[status] || '未知'
}

// 获取账号状态样式
const getAccountStatusClass = (status) => {
  return status === 1 ? 'active' : 'inactive'
}

// 获取账号状态文本
const getAccountStatusText = (status) => {
  return status === 1 ? '正常' : '已禁用'
}

// 临时测试数据
const getTestData = () => {
  return {
    code: 200,
    data: [
      {
        id: 8,
        userType: 1,
        userTypeName: "教师",
        loginId: "2240129419",
        realName: "李副教授",
        phone: "13800138002",
        email: "li@university.edu",
        college: null,
        professionalTitle: "副教授",
        auditStatus: 1,
        status: 1,
        createTime: "2025-07-28T10:00:00",
        updateTime: "2025-07-28T01:48:49"
      },
      {
        id: 56,
        userType: 2,
        userTypeName: "学生",
        loginId: "S041",
        realName: "小文",
        phone: "13800138001",
        email: "xiaowen@student.edu",
        college: "计算机科学与技术学院",
        professionalTitle: null,
        auditStatus: 1,
        status: 1,
        createTime: "2025-07-28T10:00:00",
        updateTime: "2025-07-28T01:48:49"
      }
    ]
  }
}

// 加载用户数据
const loadUserData = async () => {
  loading.value = true
  try {
    if (currentTab.value === 'all') {
      // 加载全部用户数据（教师+学生）
      await loadAllUsersData()
    } else {
      // 加载特定类型用户数据
      await loadSpecificUserData()
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败')
  } finally {
    loading.value = false
  }
}

// 加载全部用户数据
const loadAllUsersData = async () => {
  try {
    // 同时加载教师和学生数据（获取所有数据用于前端分页）
    const [teachersResult, studentsResult] = await Promise.allSettled([
      getTeachersService(1, 1000, searchKeyword.value).catch(() => ({ code: 200, data: getTestData().data.filter(u => u.userType === 1) })),
      getStudentsService(1, 1000, searchKeyword.value).catch(() => ({ code: 200, data: getTestData().data.filter(u => u.userType === 2) }))
    ])

    // 处理教师数据
    if (teachersResult.status === 'fulfilled' && teachersResult.value.code === 200) {
      const teacherData = teachersResult.value.data.list || teachersResult.value.data || []
      teachers.value = teacherData.filter(user => user.userType === 1)
      teacherTotal.value = teachers.value.length
    }

    // 处理学生数据
    if (studentsResult.status === 'fulfilled' && studentsResult.value.code === 200) {
      const studentData = studentsResult.value.data.list || studentsResult.value.data || []
      students.value = studentData.filter(user => user.userType === 2)
      studentTotal.value = students.value.length
    }

    // 计算总页数（基于所有用户）
    const totalUsers = teacherTotal.value + studentTotal.value
    totalPages.value = Math.ceil(totalUsers / pageSize)

    console.log(`总用户数: ${totalUsers}, 每页: ${pageSize}, 总页数: ${totalPages.value}`) // 调试信息
  } catch (error) {
    console.error('加载全部用户数据失败:', error)
    // 使用测试数据作为后备
    const testData = getTestData().data
    teachers.value = testData.filter(user => user.userType === 1)
    students.value = testData.filter(user => user.userType === 2)
    teacherTotal.value = teachers.value.length
    studentTotal.value = students.value.length

    // 计算总页数
    const totalUsers = teacherTotal.value + studentTotal.value
    totalPages.value = Math.ceil(totalUsers / pageSize)
  }
}

// 加载特定类型用户数据
const loadSpecificUserData = async () => {
  let result

  // 尝试从API加载数据，如果失败则使用测试数据
  try {
    if (currentTab.value === 'teachers') {
      // 获取所有教师数据用于前端分页
      result = await getTeachersService(1, 1000, searchKeyword.value)
    } else {
      // 获取所有学生数据用于前端分页
      result = await getStudentsService(1, 1000, searchKeyword.value)
    }
  } catch (apiError) {
    console.log('API调用失败，使用测试数据:', apiError)
    result = getTestData()
  }

  console.log('数据加载结果:', result) // 调试信息

  if (result.code === 200) {
    // 根据实际返回的数据格式进行适配
    const userData = result.data.list || result.data || []
    console.log('处理后的用户数据:', userData) // 调试信息

    if (currentTab.value === 'teachers') {
      // 筛选教师数据
      teachers.value = userData.filter(user => user.userType === 1)
      teacherTotal.value = teachers.value.length
      console.log('教师数据:', teachers.value) // 调试信息
      // 计算教师分页
      totalPages.value = Math.ceil(teacherTotal.value / pageSize)
    } else {
      // 筛选学生数据
      students.value = userData.filter(user => user.userType === 2)
      studentTotal.value = students.value.length
      console.log('学生数据:', students.value) // 调试信息
      // 计算学生分页
      totalPages.value = Math.ceil(studentTotal.value / pageSize)
    }

    console.log(`当前标签: ${currentTab.value}, 数据总数: ${currentTab.value === 'teachers' ? teacherTotal.value : studentTotal.value}, 总页数: ${totalPages.value}`) // 调试信息
  }
}

// 加载驳回用户数据
const loadRejectedUsers = async () => {
  loading.value = true
  try {
    const result = await getRejectedUsersService()
    if (result.code === 200) {
      rejectedUsers.value = result.data || []
      // 计算驳回用户分页
      totalPages.value = Math.ceil(rejectedUsers.value.length / pageSize)
      console.log(`驳回用户数: ${rejectedUsers.value.length}, 总页数: ${totalPages.value}`) // 调试信息
    }
  } catch (error) {
    console.error('加载驳回用户失败:', error)
    ElMessage.error('加载驳回用户失败')
  } finally {
    loading.value = false
  }
}

// 加载注销用户数据
const loadDeactivatedUsers = async () => {
  loading.value = true
  try {
    const result = await getDeactivatedUsersService()
    if (result.code === 200) {
      deactivatedUsers.value = result.data || []
      // 计算注销用户分页
      totalPages.value = Math.ceil(deactivatedUsers.value.length / pageSize)
      console.log(`注销用户数: ${deactivatedUsers.value.length}, 总页数: ${totalPages.value}`) // 调试信息
    }
  } catch (error) {
    console.error('加载注销用户失败:', error)
    ElMessage.error('加载注销用户失败')
  } finally {
    loading.value = false
  }
}

// 查看用户详情
const viewUserDetail = async (user) => {
  try {
    // 获取完整的用户详情
    const result = await getUserDetailService(user.loginId, user.userType)
    console.log('用户详情API返回:', result) // 调试信息
    if (result.code === 200) {
      selectedUser.value = result.data
      console.log('用户详情数据:', selectedUser.value) // 调试信息
      console.log('用户技能数据:', selectedUser.value.skills) // 调试技能数据
      showDetailModal.value = true
    } else {
      ElMessage.error('获取用户详情失败')
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    ElMessage.error('获取用户详情失败')
  }
}

// 处理用户注销
const handleDeactivate = (user) => {
  confirmModal.value = {
    title: '确认注销',
    message: `确定要注销用户 ${user.realName || user.loginId} 吗？注销后用户将无法登录系统。`,
    type: 'deactivate',
    user: user
  }
  showConfirmModal.value = true
}

// 处理用户启用
const handleActivate = (user) => {
  confirmModal.value = {
    title: '确认启用',
    message: `确定要启用用户 ${user.realName || user.loginId} 吗？启用后用户可以正常使用系统。`,
    type: 'activate',
    user: user
  }
  showConfirmModal.value = true
}

// 编辑用户
const editUser = async (user) => {
  try {
    // 获取完整的用户详情用于编辑
    const result = await getUserDetailService(user.loginId, user.userType)
    if (result.code === 200) {
      const userDetail = result.data

      // 填充编辑表单
      editForm.value = {
        id: userDetail.id,
        userType: userDetail.userType,
        realName: userDetail.realName || '',
        email: userDetail.email || '',
        phone: userDetail.phone || '',
        professionalTitle: userDetail.professionalTitle || '',
        idCard: userDetail.idCard || '',
        college: userDetail.college || '',
        age: userDetail.age || null,
        skillIds: userDetail.skills ? userDetail.skills.map(skillName => {
          // 根据技能名称找到对应的ID
          const skill = availableSkills.value.find(s => s.name === skillName)
          return skill ? skill.id : null
        }).filter(id => id !== null) : []
      }

      console.log('编辑用户数据:', userDetail) // 调试信息
      console.log('用户技能数据:', userDetail.skills) // 调试技能数据
      console.log('编辑表单数据:', editForm.value) // 调试表单数据

      showEditModal.value = true
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 切换技能选择
const toggleSkill = (skillId) => {
  const index = editForm.value.skillIds.indexOf(skillId)
  if (index > -1) {
    editForm.value.skillIds.splice(index, 1)
  } else {
    editForm.value.skillIds.push(skillId)
  }
}

// 保存用户信息
const saveUserInfo = async () => {
  // 验证必填字段
  if (!editForm.value.realName || !editForm.value.realName.trim()) {
    ElMessage.error('姓名不能为空')
    return
  }

  if (!editForm.value.email || !editForm.value.email.trim()) {
    ElMessage.error('邮箱不能为空')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(editForm.value.email.trim())) {
    ElMessage.error('请输入有效的邮箱地址')
    return
  }

  processing.value = true
  try {
    const updateData = {
      id: editForm.value.id,
      userType: editForm.value.userType,
      realName: editForm.value.realName.trim(),
      email: editForm.value.email.trim()
    }

    // 添加所有可能的字段（确保不发送空字符串）
    if (editForm.value.phone && editForm.value.phone.trim()) {
      updateData.phone = editForm.value.phone.trim()
    }
    if (editForm.value.age && editForm.value.age > 0) {
      updateData.age = editForm.value.age
    }
    if (editForm.value.idCard && editForm.value.idCard.trim()) {
      updateData.idCard = editForm.value.idCard.trim()
    }

    // 根据用户类型添加特定字段
    if (editForm.value.userType === 1) {
      // 教师特有字段
      if (editForm.value.professionalTitle && editForm.value.professionalTitle.trim()) {
        updateData.professionalTitle = editForm.value.professionalTitle.trim()
      }
    } else {
      // 学生特有字段
      if (editForm.value.college && editForm.value.college.trim()) {
        updateData.college = editForm.value.college.trim()
      }

      // 技能数据处理
      const skillNames = editForm.value.skillIds.map(skillId => {
        const skill = availableSkills.value.find(s => s.id === skillId)
        return skill ? skill.name : null
      }).filter(name => name !== null)

      // 根据后端API文档，尝试不同的格式
      // 格式1: 技能名称数组
      updateData.skills = skillNames

      // 格式2: 技能ID数组（备用）
      // updateData.skillIds = editForm.value.skillIds

      // 格式3: 技能对象数组（备用）
      // updateData.skills = editForm.value.skillIds.map(skillId => {
      //   const skill = availableSkills.value.find(s => s.id === skillId)
      //   return skill ? { id: skill.id, name: skill.name } : null
      // }).filter(skill => skill !== null)

      console.log('学生技能数据处理:', {
        原始skillIds: editForm.value.skillIds,
        转换后skillNames: skillNames,
        最终发送的skills: updateData.skills
      }) // 调试信息
    }

    console.log('=== 用户更新调试信息 ===')
    console.log('发送更新数据:', updateData)
    console.log('发送更新数据JSON:', JSON.stringify(updateData, null, 2))

    // 特别关注技能数据
    if (updateData.skills) {
      console.log('技能数据详情:', {
        类型: typeof updateData.skills,
        长度: updateData.skills.length,
        内容: updateData.skills,
        是否为数组: Array.isArray(updateData.skills)
      })
    }

    const result = await updateUserService(updateData)
    console.log('更新用户API返回:', result)

    if (result.code === 200) {
      ElMessage.success('用户信息更新成功')



      closeEditModal()

      // 等待一下再重新加载数据，确保后端已经保存
      setTimeout(async () => {
        if (statusFilter.value === 'rejected') {
          await loadRejectedUsers()
        } else if (statusFilter.value === 'deactivated') {
          await loadDeactivatedUsers()
        } else {
          await loadUserData()
        }
      }, 500)
    } else {
      ElMessage.error(result.message || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)

    // 处理不同类型的错误
    if (error.response && error.response.data) {
      const errorData = error.response.data
      if (errorData.errors && errorData.errors.length > 0) {
        // 显示第一个验证错误
        const firstError = errorData.errors[0]
        if (firstError.cause && firstError.cause.field) {
          const fieldName = getFieldDisplayName(firstError.cause.field)
          ElMessage.error(`${fieldName}${firstError.cause.defaultMessage || '格式不正确'}`)
        } else {
          ElMessage.error(firstError.defaultMessage || '数据验证失败')
        }
      } else {
        ElMessage.error(errorData.message || '更新失败')
      }
    } 
  } finally {
    processing.value = false
  }
}

// 获取字段显示名称
const getFieldDisplayName = (fieldName) => {
  const fieldMap = {
    'realName': '姓名',
    'email': '邮箱',
    'phone': '手机号',
    'age': '年龄',
    'idCard': '身份证号',
    'professionalTitle': '职位',
    'college': '学院'
  }
  return fieldMap[fieldName] || fieldName
}

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditModal.value = false
  editForm.value = {
    id: null,
    userType: null,
    realName: '',
    email: '',
    phone: '',
    professionalTitle: '',
    idCard: '',
    college: '',
    age: null,
    skillIds: []
  }
}

// 确认操作
const confirmAction = async () => {
  processing.value = true
  try {
    const { type, user } = confirmModal.value

    let result
    if (type === 'deactivate') {
      result = await deactivateUserService(user.id, user.userType)
    } else if (type === 'activate') {
      result = await activateUserService(user.id, user.userType)
    }
    
    if (result.code === 200) {
      ElMessage.success(`用户${type === 'deactivate' ? '注销' : '启用'}成功`)
      await loadUserData() // 重新加载数据
    } else {
      ElMessage.error(result.message || '操作失败')
    }

    closeConfirmModal()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    processing.value = false
  }
}

// 关闭弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedUser.value = null
}

const closeConfirmModal = () => {
  showConfirmModal.value = false
}

// 切换页面
const changePage = (page) => {
  currentPage.value = page
  // 不需要重新加载数据，因为使用前端分页
  // currentUsers计算属性会自动更新显示的数据
}

// 处理文件下载
const handleFileDownload = (blob, filename) => {
  try {
    // 检查响应是否为空
    if (!blob || blob.size === 0) {
      throw new Error('导出的文件为空')
    }
    
    // 检查响应类型
    const contentType = blob.type
    if (!contentType.includes('spreadsheetml.sheet') && !contentType.includes('ms-excel')) {
      throw new Error('导出的文件格式不正确')
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    
    // 清理资源
    window.URL.revokeObjectURL(url)
    document.body.removeChild(link)
    
    return true
  } catch (error) {
    console.error('文件下载失败:', error)
    throw error
  }
}

// 导出当前数据
const handleExportData = async () => {
  if (isExporting.value) return
  
  isExporting.value = true
  try {
    let exportService
    let filename
    
    // 根据当前状态筛选选择对应的导出接口
    if (statusFilter.value === 'rejected') {
      exportService = exportRejectedUsersService
      filename = `被驳回用户数据_${new Date().toLocaleDateString()}.xlsx`
      ElMessage.info('正在导出被驳回用户数据，请稍候...')
    } else if (statusFilter.value === 'deactivated') {
      exportService = exportDeactivatedUsersService
      filename = `被注销用户数据_${new Date().toLocaleDateString()}.xlsx`
      ElMessage.info('正在导出被注销用户数据，请稍候...')
    } else {
      exportService = exportAllUsersService
      filename = `全部用户数据_${new Date().toLocaleDateString()}.xlsx`
      ElMessage.info('正在导出全部用户数据，请稍候...')
    }
    
    const response = await exportService()
    
    // 处理文件下载
    handleFileDownload(response, filename)
    
    ElMessage.success('导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(error.message || '导出失败，请重试')
  } finally {
    isExporting.value = false
  }
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadUserData()
  loadSkillsList() // 加载技能列表
})
</script>

<style scoped>
@import '@/assets/admin-common.css';
@import '@/assets/css/UserManagement.css';

/* 导出按钮样式 */
.export-actions {
  flex-shrink: 0;
  margin-left: 16px;
}

.export-btn {
  background: #52c41a;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 140px;
  justify-content: center;
}

.export-btn:hover:not(:disabled) {
  background: #73d13d;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.export-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.export-btn.loading {
  background: #faad14;
}

.export-btn.loading:hover {
  background: #ffc53d;
}
</style>
